package com.cloudcc.mobile.view.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.adapter.ViewHolder;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.net.async.JsonRequest;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.BaseOneChoiceAdapter;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.LoginPresenter;
import com.cloudcc.mobile.util.AESUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UIUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.wel.GuideViewActivity;
import com.google.gson.JsonObject;
import com.loopj.android.http.RequestParams;

/**
 * 快速进入第三步 选择角色
 * 
 * @Description: TODO()
 * @author wangzhiqiang
 * @date 2016-3-3 下午3:44:34
 * 
 */
public class Step3Fragment extends BaseStepFragment implements IEventLife{


	@Bind(R.id.test_done)
	Button btn_done;

	@Bind(R.id.listview)
	ListView mlistView;
	private LoginPresenter loginPresenter = new LoginPresenter();
	private RoleChoiceAdapter mAdapter;

	private RoleTestUserName roleTestUser;

	@Override
	public void init() {
		super.init();
		register();

		initChoiceData();

	}

	private void initChoiceData() {
		List<RoleTestUserName> datas = new ArrayList<RoleTestUserName>();
		datas.add(new RoleTestUserName("老板(CEO)", "boss@cloudcc.com", "yzegda"));
		datas.add(new RoleTestUserName("销售经理/销售代表", "sales@cloudcc.com",
				"TswjCy"));
		mAdapter = new RoleChoiceAdapter(getActivity());
		mlistView.setAdapter(mAdapter);
		mAdapter.changeData(datas);
	}

	@OnClick(R.id.test_done)
	public void clickDone() {

		if (mAdapter == null) {
			return;
		}
		roleTestUser = mAdapter.getItem(mAdapter.getSelectPost());
		String url = "http://app9.cloudcc.com";
		UrlTools.url = url + "/";
		UrlManager.APP_UR = url;
		UrlTools.weixinUrl = url;
		showWainting("请稍等...");
		
		loginPresenter.login(roleTestUser.userName, roleTestUser.password);

	}
	/**
	 * 登录数据返回
	 * 
	 * @param event
	 */
	public void onEventMainThread(LoginEvent event) {
		if (event.isError()) {
			showToast("亲,不好意思登录失败,请重新尝试体验。。。");
			return;
		}
		String enPassword = StringUtils.EMPTY;
		try {
			enPassword = AESUtils.encrypt(Tools.getpassword(),roleTestUser.password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (StringUtils.isNotBlank(enPassword)) {// 将用户名密码保存到db中记录
			loginPresenter.saveLoginToHistory(roleTestUser.userName, enPassword,false,false,false);
		}
		RunTimeManager.setAppBinding(event.getData().binding);
		RunTimeManager.getInstance().setTestModel(true);
		final UserModel user = event.getData().userInfo;
		UserManager.getManager().saveUser(user);
		insertLeads();
	}
	
	/**
	 * 插入潜在客户
	 */
	private void insertLeads(){
		HashMap<String, String> data = new HashMap<String, String>();
		data.put("name", "安卓手机快速体验");
		data.put("phone", mParentActivity.getTestPhoneMobile());
		List aa =new ArrayList<>();
		aa.add(data);
		RequestParams params = new RequestParams();
		params.put("serviceName", "insert");
		params.put("objectApiName", "Lead");
		params.put("data", GsonUtil.Object2Json(aa));
		params.put("binding", mParentActivity.testBinding);
		AsyncClient.getInstance().post(
				"http://app.cloudcc.com/distributor.action", params,
				new myJsonRequest());
	}
	private class myJsonRequest extends JsonRequest {

		@Override
		public void handleFailure(ErrorInfo arg0) {
			dismissWainting();
			enterAPP();
		}

		@Override
		public void handleSuccess(JsonObject arg0, String arg1) {
			dismissWainting();
			enterAPP();
		}
	}
	/**
	 * 进入app
	 */
	private void enterAPP() {
		AppContext.isFenXiang = false;
		UIUtils.enterMainUI(mContext);
		AppManager.getInstance().finishActivity(GuideViewActivity.class);
		getActivity().finish();
	}
	private class RoleTestUserName {

		public RoleTestUserName(String title, String userName, String password) {
			super();
			this.title = title;
			this.userName = userName;
			this.password = password;
		}

		public String title;
		public String userName;
		public String password;

	}

	private class RoleChoiceAdapter extends BaseOneChoiceAdapter<RoleTestUserName> {

		public RoleChoiceAdapter(Context mContext) {
			super(mContext);
		}

		@Override
		public int getLayoutId() {
			return R.layout.role_list_item;
		}

		@Override
		public void convert(ViewHolder h, RoleTestUserName t) {
			h.setText(R.id.tv1, t.title);
			ImageView image = h.getView(R.id.iv1);
			if (mSelectPos == h.getPostion()) {
				image.setImageResource(R.drawable.added_item);
			} else {
				image.setImageDrawable(new ColorDrawable(Color.TRANSPARENT));
			}
			final int pos = h.getPostion();
			final RoleTestUserName tt = t;
			h.getConvertView().setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mSelectPos = pos;
					notifyDataSetChanged();
				}
			});

		}

	}

	@Override
	public void onDestroy() {
		unRegister();
		super.onDestroy();
	}

	@Override
	public int getLayoutId() {
		return R.layout.test_step3;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

}
